<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Category extends Admin_Controller {

	public function __construct() {
		parent::__construct();
		$this->load->model('admin/'. __CLASS__ .'_model', 'model');
	}

	public function index() {
		$data = [];
		$data['lists'] = $this->sort_level($this->model->get_lists());

		$data['nav'] = $this->get_nav();
		$this->load->view($this->view, $data);
	}

	//显示添加模板
	public function add() {
		$data = [];

		//添加
		if ('POST' == $this->input->server('REQUEST_METHOD')) {
			$lang = config_item('lang');
			$insert_id = $this->model->insert();
			if (empty($insert_id)) {
				$this->error([
					'url' => $this->input->server('HTTP_REFERER'),
					'message' => $this->model->error,
				]);
			}
			$this->success([
				'url' => site_url('admin/category/add/'. $this->input->post('parent_id')),
				'message' => $lang['action_success'],
			]);
		}
		$data['lists'] = $this->sort_level($this->model->get_lists(['id', 'parent_id', 'name']));

		$data['nav'] = $this->get_nav();
		$this->load->view($this->view, $data);
	}

	//显示编辑模板
	public function edit($id = 0) {
		$data = [];
		$lang = config_item('lang');

		$id = (int) $id;
		if (empty($id)) {
			$this->error([
				'url' => $this->input->server('HTTP_REFERER'),
				'message' => $lang['method_illegal'],
			]);
		}

		$where = ['id' => $id];
		//编辑
		if ('POST' == $this->input->server('REQUEST_METHOD')) {
			$affected_rows = $this->model->update($where);
			if (empty($affected_rows)) {
				$this->error([
					'url' => $this->input->server('HTTP_REFERER'),
					'message' => $lang['action_error'],
				]);
			}
			$this->success([
				'url' => site_url('admin/category/index'),
				'message' => $lang['action_success'],
			]);
		}

		$data['row'] = $this->model->get_row($where);
		if (empty($data['row'])) {
			$this->error([
				'url' => url(),
				'message' => $lang['data_illegal'],
			]);
		}
		$data['lists'] = $this->sort_level($this->model->get_lists(['id', 'parent_id', 'name'], ['id != ' => $data['row']['id']]));

		$data['nav'] = $this->get_nav();
		
		$this->load->view($this->view, $data);
	}

	//删除
	public function del() {
		$lang = config_item('lang');
		$id = (int) $this->uri->segment(4, 0);
		if (empty($id)) {
			$this->error([
				'url' => $this->input->server('HTTP_REFERER'),
				'message' => $lang['method_illegal'],
			]);
		}

		$id = [$id];
		$lists = $this->model->get_lists(['id', 'parent_id']);
		foreach ($lists as $key => $value) {
			in_array($value['parent_id'], $id) AND $id[] = $value['id'];
		}

		$where = 'id IN('. implode(',', $id) .')';
		$affected_rows = $this->model->delete($where);
		if (empty($affected_rows)) {
			$this->error([
				'url' => $this->input->server('HTTP_REFERER'),
				'message' => $lang['action_error'],
			]);
		}
		$this->load->model('admin/Info_model');
		$where = 'infocate_id IN('. implode(',', $id) .')';
		$this->Info_model->delete($where);
		redirect('admin/category/index');
	}
}
